<template>
	<view class="questionnaire-container home-wrap" :style="{ 'background':'#fff'}">
		<shopro-navbar :isFixed="true" :isBack="true" :background="{'background':'#fff'}">
			<view slot="content" class="u-flex u-flex-center u-flex-items-center" style="color: #000; width: 85%; text-align: center;padding-left: 20rpx;height: 100%;">
				<text class="chapter" v-html="currentQuestion.title"></text>
			</view>
		</shopro-navbar>
		<view class="u-m-l-20">
			<text class="progress u-m-r-20" v-if="currentQuestion.kind_text">
				{{currentQuestion.kind_text}}
			</text>
			<text class="number" v-if="totalQuestions > 0">
				{{ currentIndex + 1 }}/{{ totalQuestions }}
			</text>
		</view>
		<!-- 题目内容 -->
		<view class="question" v-html="currentQuestion.title"></view>
		<!-- 选项列表 -->
		<view class="options" v-if="currentQuestion && currentQuestion.kind_text !== '填空题'">
			<view
				v-for="(option, idx) in currentQuestion.options_json"
				:key="idx"
				:class="{
				    'option': true,
				    'selected':  (myAnswer || []).includes(option.key),
				    'selected':  (
				      (currentQuestion.kind_text === '多选题' ? (selectedOption || []).includes(option.key) : selectedOption === option.key)
				    )
				  }"
				@click="selectOption(option.key)">
				<text class="option-label">{{ option.key }}</text>
				<text class="option-text">{{ option.value }}</text>
			</view>
		</view>
		<!-- 填空题输入框 -->
		<view v-if="currentQuestion.kind_text === '填空题'" class="options">
			<input class="blank-input" type="text" v-model="selectedOption" placeholder="请输入答案" @input="onInputBlank" />
		</view>
		
		<!-- 下一题、上一题按钮 -->
		<view class="next-btn-wrapper u-flex u-flex-between u-flex-items-center" v-if="selectedOption !== null || currentIndex > 0">
			<view class="btn pre-btn u-flex u-flex-items-center u-flex-center" @click="goToPre">
				上一题
			</view>
			<view class="btn next-btn u-flex u-flex-items-center u-flex-center" @click="goToNext" v-if="currentIndex !== questions.length -1">
				下一题
			</view>
		</view>
		
		<!-- 底部操作按钮 -->
		<view class="bottom-bar">
			<view
				class="bar-btn u-flex u-flex-column u-flex-center u-flex-items-center"
				:class="[{active: activeBar==='wrong'}, {disabled: isInWrongBook}]"
				@click="onBarClick('wrong')">
				<image :src="HTTP_IMG_URL()+'/static/images/switchTabbar/jiarucuoti2.png'" mode="" v-if="isInWrongBook"></image>
				<image :src="HTTP_IMG_URL()+'/static/images/switchTabbar/jiarucuoti.png'" mode="" v-else></image>
				<view>{{ isInWrongBook ? '已加入错题' : '加入错题' }}</view>
			</view>
			<view class="bar-btn u-flex u-flex-column u-flex-center u-flex-items-center"  @click="onBarClick('analysis')">
				<image :src="HTTP_IMG_URL()+'/static/images/switchTabbar/chakanjiexi.png'" mode="" v-if="activeBar==='analysis'"></image>
				<image :src="HTTP_IMG_URL()+'/static/images/switchTabbar/chakanjiexi.png'" mode="" v-else></image>
				<view>查看解析</view>
			</view>
			<view class="bar-btn u-flex u-flex-column u-flex-center u-flex-items-center"  @click="onBarClick('card')">
				<image :src="HTTP_IMG_URL()+'/static/images/switchTabbar/datika.png'" mode="" v-if="activeBar==='card'"></image>
				<image :src="HTTP_IMG_URL()+'/static/images/switchTabbar/datika.png'" mode="" v-else></image>
				<view>答题卡</view>
			</view>
		</view>
		
		<!-- 解析内容 -->
		<view v-if="activeBar==='analysis'" class="analysis-section">
			<view class="answer-row">
				<view class="answer-label correct">● 正确答案：</view>
				<view class="answer-value correct">
					<text class="answer-link correct">{{ correctAnswerText }}</text>
				</view>
				<view class="answer-label mine">我的答案：</view>
				<view class="answer-value mine">
					<text :class="['answer-link', myAnswer ? 'mine-active' : 'mine']">
						{{ myAnswerText }}
					</text>
				</view>
			</view>
			<view class="analysis-title-row">
				<view class="dot">●</view>
				<view class="analysis-title">解析</view>
			</view>
			<!-- <video
				class="analysis-video"
				:src="currentQuestion.analysisVideo"
				controls
				style="width: 100%; height: 300rpx; border-radius: 16rpx; margin-top: 16rpx;"
				@ended="showVideo = false"
				@close="showVideo = false"
			/> -->
			<view class="analysis-text" v-html="currentQuestion.explain"></view>
			<!-- <video
				v-if="showVideo"
				:src="currentQuestion.analysisVideo"
				controls
				autoplay
				style="width: 100%; height: 300rpx; border-radius: 16rpx; margin-top: 16rpx;"
				@ended="showVideo = false"
				@close="showVideo = false"
			/> -->
		</view>
		<SuccessModal
			:title="'添加成功'"
			:desc="'已添加在错题本中'"
			:show="showSuccessModal"
			@close="showSuccessModal = false">
		</SuccessModal>
		
		<!-- 答题卡只在activeBar==='card'时显示 -->
		<view v-if="activeBar==='card'" class="card-modal-mask" @click.self="activeBar = ''">
			<view class="card-modal">
				<view class="card-modal-header">
					<text class="card-modal-title">答题卡</text>
					<view class="card-modal-close">
						<u-icon name="close" size="20" color="#bbb" @click="activeBar = ''" />
					</view>
				</view>
				<view class="card-modal-body">
					<view class="card-grid">
						<view
							v-for="(q, idx) in questions"
							:key="idx"
							:class="{
							    'card-item': true,
							    'current': item.answer === userAnswers[idx],
							    'done': userAnswers[idx],
							    'undone': !userAnswers[idx]
							  }"
							@click="jumpToQuestion(idx)">
							{{ idx + 1 }}
						</view>
					</view>
					<view class="card-legend">
						<view class="legend-item"><view class="legend-dot current"></view>当前</view>
						<view class="legend-item"><view class="legend-dot done"></view>已做</view>
						<view class="legend-item"><view class="legend-dot undone"></view>未做</view>
					</view>
				</view>
				<view class="card-modal-footer">
					<view class="card-btn outline u-flex u-flex-center u-flex-items-center" @click="activeBar = ''">下次继续</view>
					<view class="card-btn primary u-flex u-flex-center u-flex-items-center" @click="submitPaper">提交</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import SuccessModal from '@/components/SuccessModal.vue';
import { record } from '@/api'
export default {
	components: {
		SuccessModal
	},
	data() {
		// 补齐题目数量
		let questions = [];
		return {
			questions,
			currentIndex: 0,
			selectedOption: null,
			userAnswers: [], // 记录每题作答
			showAnalysis: false,
			wrongBook: [], // 错题本
			showSuccessModal: false,
			showVideo: false,
			showCard: false,
			activeBar: '',
			correctAnswerText: '',
			totalQuestions: 0,
			paperId: ''
		};
	},
	computed: {
		currentQuestion() {
			return this.questions[this.currentIndex];
		},
		myAnswer() {
			// 返回当前题的作答
			return this.userAnswers[this.currentIndex] || null;
		},
		myAnswerText() {
			if (!this.myAnswer) return '未作答';
			// 多选/单选统一处理
			if (Array.isArray(this.myAnswer)) {
				return this.myAnswer.join('');
			}
			return this.myAnswer;
		},
		isInWrongBook() {
			const q = this.questions[this.currentIndex];
			return this.wrongBook.some(item => item.question === q.question);
			// 可根据唯一id判断，若有id字段
		},
	},
	methods: {
		async getQuestionList (id) {
			console.log(id, 'eee');
			const res = await record.getQuestionTrain({
				cate_id: id
			}).then((res) => {
				if (res.response.data.code == 1) {
					this.questions = res.response.data.data.data;
					this.totalQuestions = res.response.data.data.total;
					console.log(res.response.data.data.total, 'eeeesss');
				}
			})
		},
		HTTP_IMG_URL() {
			return this.$imgUrl;
		},
		selectOption(value) {
			const type = this.currentQuestion.kind_text;
			if (type === '单选题' || type === '判断题') {
				this.selectedOption = value;
				this.$set(this.userAnswers, this.currentIndex, [value]);
			} else if (type === '多选题') {
				let arr = Array.isArray(this.selectedOption) ? [...this.selectedOption] : [];
				const idx = arr.indexOf(value);
				if (idx > -1) {
					arr.splice(idx, 1);
				} else {
					arr.push(value);
				}
				this.selectedOption = arr;
				this.$set(this.userAnswers, this.currentIndex, arr);
			} // 填空题用input事件处理
		},
		onInputBlank(e) {
			const val = e.detail.value;
			this.selectedOption = val;
			this.$set(this.userAnswers, this.currentIndex, val ? [val] : []);
		},
		goToPre() {
			if (this.currentIndex > 0) {
				this.currentIndex--;
				const type = this.questions[this.currentIndex].type;
				if (type === '多选题') {
					this.selectedOption = this.userAnswers[this.currentIndex] ? [...this.userAnswers[this.currentIndex]] : [];
				} else if (type === '填空题') {
					this.selectedOption = this.userAnswers[this.currentIndex]?.[0] || '';
				} else {
					this.selectedOption = this.userAnswers[this.currentIndex]?.[0] || null;
				}
				this.showAnalysis = false;
				this.activeBar = '';
			} else {
				uni.showToast({ title: '已是第一题', icon: 'none' });
			}
		},
		goToNext() {
			if (this.currentIndex < this.questions.length - 1) {
				this.currentIndex++;
				const type = this.questions[this.currentIndex].type;
				if (type === '多选题') {
					this.selectedOption = this.userAnswers[this.currentIndex] ? [...this.userAnswers[this.currentIndex]] : [];
				} else if (type === '填空题') {
					this.selectedOption = this.userAnswers[this.currentIndex]?.[0] || '';
				} else {
					this.selectedOption = this.userAnswers[this.currentIndex]?.[0] || null;
				}
				this.showAnalysis = false;
				this.activeBar = '';
			} else {
				uni.showToast({ title: '已是最后一题', icon: 'none' });
			}
		},
		addToWrongBook() {
			const q = this.questions[this.currentIndex];
			const exists = this.wrongBook.some(item => item.question === q.question);
			if (exists) {
				uni.showToast({ title: '已加入错题本', icon: 'none' });
				return;
			}
			this.wrongBook.push(q);
			this.showSuccessModal = true;
		},
		playAnalysisVideo() {
			this.showVideo = true;
		},
		cardClass(idx) {
			if (idx === this.currentIndex) return ['card-item', 'current'];
			if (this.userAnswers[idx]) return ['card-item', 'done'];
			return ['card-item', 'undone'];
		},
		jumpToQuestion(idx) {
			this.currentIndex = idx;
			this.selectedOption = this.userAnswers[idx]?.[0] || null;
			this.activeBar = '';
		},
		async submitPaper() {
			// 校验所有题是否已作答
			const notDone = this.questions.findIndex((q, idx) => q.question && !this.userAnswers[idx]);
			if (notDone !== -1) {
				uni.showToast({ title: `第${notDone + 1}题未作答`, icon: 'none' });
				return;
			}
			console.log(this.questions, 'this.questionsthis.questions');
			const questionArr = this.questions.map((item, index) => {
				return {
					id: item.id,
					answer: String(this.userAnswers[index]),
					material_id: 0
				}
			})
			let questionsObject = {};
			questionArr.forEach((item, index) => {
				questionsObject[index] = item;
			});
			console.log(questionsObject, 'questionArrquestionArr');
			const res = await record.submitPaper({
				paper_id: this.paperId,
				questions: questionsObject
			}).then((res) => {
				if (res.response.data.code == 1) {
					console.log(res.response.data.data, 'eeeesss');
					const answerObj = res.response.data.data;
					uni.showToast({ title: '提交成功', icon: 'success' });
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/questionnaire/answer?answerStr=' + JSON.stringify(answerObj),
						});
					}, 800);
				}
			})
		},
		onBarClick(key) {
			if (key === 'wrong') {
				this.addToWrongBook();
				// 不改变activeBar
			} else if (key === 'analysis') {
				// toggle 解析
				this.activeBar = this.activeBar === 'analysis' ? '' : 'analysis';
				this.correctAnswerText = this.currentQuestion.answer;
			} else if (key === 'card') {
				this.activeBar = 'card';
			}
		},
	},
	beforeDestroy() {
		uni.removeStorageSync('catId');
	},
	onLoad(options) {
		const cateid = options.catId;
		this.paperId = options.catId;
		this.getQuestionList(cateid);
		if(options.type){
			this.activeBar='analysis';
		}
	},
};
</script>

<style lang="scss">
.questionnaire-container {
	min-height: 100vh;
	display: flex;
	flex-direction: column;
	background: #fafafa;
	padding-bottom: 60px;
}
.header {
	padding: 24rpx 32rpx 0 32rpx;
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}
.chapter {
}
.progress {
	min-width: 90rpx;
	font-size: 24rpx;
	color: #1664FF;
	background: rgba(22,100,255,0.06);
	border-radius: 4px;
	border: 1px solid rgba(22,100,255,0.06);
	padding: 4rpx 8rpx;
	border-image: linear-gradient(180deg, rgba(253, 244, 245, 1), rgba(250, 230, 232, 1)) 1 1;
}
.number{
	min-width: 90rpx;
	font-size: 24rpx;
	color:#666666;
	border-radius: 4px;
	padding: 4rpx 8rpx;
	border: 1px solid #EEEEEE;
}
.question {
	margin: 32rpx 32rpx 0 32rpx;
	font-size: 30rpx;
	font-weight: 500;
}
.options {
	margin: 32rpx 32rpx 0 32rpx;
	display: flex;
	flex-direction: column;
	gap: 24rpx;
}
.option {
	display: flex;
	align-items: center;
	padding: 24rpx;
	border-radius: 16rpx;
	background: #fff;
	font-size: 28rpx;
	transition: border 0.2s;
}
.option.selected {
	.option-label {
		color: #fff;
		background: #1664FF;
		box-shadow: 0px 2px 4px 0px rgba(22,100,255,0.5);
	}
}
.option-label {
	width: 48rpx;
	height: 48rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: #f0f0f0;
	border-radius: 50%;
	margin-right: 24rpx;
	font-weight: 600;
}
.next-btn-wrapper {
	margin: 40rpx 32rpx 0 32rpx;
}
.next-btn {
	width: 45%;
	background: #007aff;
	color: #fff;
	border-radius: 12rpx;
	font-size: 30rpx;
	padding: 20rpx 0;
}
.pre-btn{
	width: 45%;
	background: #007aff;
	color: #fff;
	border-radius: 12rpx;
	font-size: 30rpx;
	padding: 20rpx 0;
}
.tabbar {
	position: fixed;
	left: 0;
	bottom: 0;
	width: 100vw;
	height: 100rpx;
	background: #fff;
	display: flex;
	border-top: 1rpx solid #eee;
	z-index: 10;
}
.tabbar-item {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	color: #888;
	transition: color 0.2s;
}
.tabbar-item.active {
	color: #007aff;
	font-weight: 600;
}
.analysis-section {
	background: #fff;
	margin: 32rpx 32rpx 0 32rpx;
	border-radius: 20rpx;
	padding: 32rpx 24rpx 40rpx 24rpx;
	box-shadow: 0 2rpx 12rpx #e6eaf0;
}
.answer-row {
	display: flex;
	align-items: center;
	font-size: 28rpx;
	margin-bottom: 16rpx;
	flex-wrap: wrap;
}
.answer-label {
	color: #2563eb;
	margin-right: 8rpx;
}
.answer-label.mine {
	color: #888;
	margin-left: 32rpx;
}
.answer-value {
	margin-right: 24rpx;
}
.answer-link {
	color: #2563eb;
	font-weight: 600;
	margin-right: 8rpx;
}
.answer-link.mine {
	color: #888;
}
.answer-link.mine-active {
	color: #f00;
	font-weight: 600;
}
.answer-link.correct {
	color: #2563eb;
	font-weight: 600;
}
.analysis-title-row {
	display: flex;
	align-items: center;
	margin: 24rpx 0 16rpx 0;
}
.dot {
	color: #2563eb;
	font-size: 28rpx;
	margin-right: 8rpx;
}
.analysis-title {
	font-size: 28rpx;
	font-weight: 600;
}
.analysis-video {
	position: relative;
	width: 100%;
	height: 240rpx;
	margin-bottom: 20rpx;
}
.analysis-img {
	width: 100%;
	height: 100%;
	border-radius: 16rpx;
	object-fit: cover;
}
.play-btn {
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
	z-index: 2;
}
.analysis-text {
	font-size: 28rpx;
	color: #333;
	line-height: 1.8;
	margin-top: 12rpx;
}
.option-correct {
	border: 2rpx solid #2563eb !important;
	background: #e6f0ff !important;
	color: #2563eb !important;
}
.option-mine {
	border: 2rpx solid #f00 !important;
	background: #ffeaea !important;
	color: #f00 !important;
}
.blank-input {
	width: 100%;
	height: 80rpx;
	border: 1rpx solid #eee;
	border-radius: 12rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
	color: #333;
}
.card-modal-mask {
	position: fixed;
	left: 0; top: 0; right: 0; bottom: 0;
	background: rgba(0,0,0,0.18);
	z-index: 1000;
	display: flex;
	align-items: flex-end;
	justify-content: center;
}
.card-modal {
	width: 100vw;
	background: #fff;
	border-radius: 32rpx 32rpx 0 0;
	box-shadow: 0 -2rpx 16rpx #e6eaf0;
	padding-bottom: env(safe-area-inset-bottom);
	animation: cardUp 0.2s;
}
@keyframes cardUp {
	from { transform: translateY(100%); }
	to { transform: translateY(0); }
}
.card-modal-header {
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
	padding: 32rpx 0 0 0;
}
.card-modal-title {
	font-size: 32rpx;
	font-weight: normal;
}
.card-modal-close {
	position: absolute;
	right: 32rpx;
	top: 32rpx;
}
.card-modal-body {
	padding: 24rpx 32rpx 0 32rpx;
}
.card-grid {
	display: flex;
	flex-wrap: wrap;
	gap: 18rpx 18rpx;
	margin-bottom: 24rpx;
}
.card-item {
	width: 64rpx;
	height: 64rpx;
	border-radius: 50%;
	background: #f5f8ff;
	color: #2563eb;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	font-weight: 500;
	transition: all 0.2s;
}
.card-item.current {
	background: #2563eb;
	color: #fff;
}
.card-item.done {
	background: #e6f0ff;
	color: #2563eb;
}
.card-item.undone {
	background: #f5f5f5;
	color: #bbb;
}
.card-legend {
	display: flex;
	justify-content: center;
	gap: 32rpx;
	margin-bottom: 12rpx;
}
.legend-item {
	display: flex;
	align-items: center;
	font-size: 24rpx;
	color: #888;
}
.legend-dot {
	width: 20rpx;
	height: 20rpx;
	border-radius: 50%;
	margin-right: 8rpx;
	display: inline-block;
}
.legend-dot.current {
	background: #2563eb;
}
.legend-dot.done {
	background: #e6f0ff;
	border: 2rpx solid #2563eb;
}
.legend-dot.undone {
	background: #f5f5f5;
	border: 2rpx solid #bbb;
}
.card-modal-footer {
	display: flex;
	gap: 24rpx;
	justify-content: space-between;
	padding: 24rpx 32rpx 32rpx 32rpx;
}
.card-btn {
	flex: 1;
	font-size: 24rpx;
	border-radius: 40rpx;
	padding: 18rpx 0;
	border: none;
}
.card-btn.outline {
	background: #fff;
	color: #2563eb;
	border: 2rpx solid #2563eb;
}
.card-btn.primary {
	background: #2563eb;
	color: #fff;
}
.bottom-bar {
	position: fixed;
	left: 0;
	bottom: 0;
	width: 100vw;
	height: 100rpx;
	background: #fff;
	display: flex;
	border-top: 1rpx solid #eee;
	z-index: 10;
}
.bar-btn {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
	color: #888;
	cursor: pointer;
	transition: color 0.2s;
	image{
		width: 40rpx;
		height: 40rpx;
		margin-bottom: 5rpx;
	}
}
.bar-btn.active {
	color: #2563eb;
}
.bar-btn.disabled {
	color: #2563eb;
}
</style>
